﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.BaseInfo.DTO.Staff;
using AnQinFrameWorkAPI.Entity.BaseInfo.Entity;
using AnQinFrameWorkAPI.Entity.BaseInfo.View.Staff;
using AnQinFrameWorkAPI.Entity.SystemCore.Entity;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.BaseInfo;

/// <summary>
///     员工业务层
/// </summary>
public class StaffService
{
    #region 获取员工列表

    public async Task<RequestResponseModel> GetStaffList(StaffSearchDTO staffSearchDTO)
    {
        //筛选
        var query = _context.Staff
                .ProjectTo<StaffView>(_mapper.ConfigurationProvider)
                .AsNoTracking()
                .WhereIF(a => a.Code.Contains(staffSearchDTO.Staff) || a.Name.Contains(staffSearchDTO.Staff),
                    !string.IsNullOrEmpty(staffSearchDTO.Staff))
                .WhereIF(a => a.DepartmentId.Contains(staffSearchDTO.DepartmentId),
                    !string.IsNullOrEmpty(staffSearchDTO.DepartmentId))
                .WhereIF(a => a.CreateTime > staffSearchDTO.StartTime, staffSearchDTO.StartTime != null)
                .WhereIF(a => a.CreateTime < staffSearchDTO.EndTime, staffSearchDTO.EndTime != null)
            ;

        //返回列表
        var staffList = await query
            .OrderBy(a => a.CreateTime)
            .Page(staffSearchDTO.PageIndex, staffSearchDTO.PageSize)
            .ToListAsync();

        //总数据量
        var pageCount = await query.CountAsync();

        //返回数据
        var pageResult = new PageResult<StaffView>(staffList, pageCount);
        return RequestResponse.OK(pageResult, "查询成功");
    }

    #endregion

    #region 新增员工

    public async Task<RequestResponseModel> AddStaff(StaffAddDTO staffAddDTO)
    {
        //生成新数据
        var staff = _mapper.Map<StaffModel>(staffAddDTO);
        staff.Id = Guid.NewGuid();
        staff.CreateTime = DateTime.Now;
        _context.Staff.Add(staff);


        //处理员工角色
        if (staffAddDTO.RoleList != null)
            foreach (var item in staffAddDTO.RoleList)
            {
                var staffRole = new StaffRoleModel
                {
                    Id = Guid.NewGuid(),
                    StaffId = staff.Id,
                    RoleId = Guid.Parse(item)
                };
                _context.StaffRole.Add(staffRole);
            }

        //保存数据
        await _context.SaveChangesAsync();
        return RequestResponse.OK(staff.Id, "新增成功");
    }

    #endregion

    #region 更新员工

    public async Task<RequestResponseModel> PutStaff(StaffUpdateDTO staffIUpdateDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.Staff, staffIUpdateDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("员工Id无效");
        ;

        //编辑数据
        var staff = _mapper.Map(staffIUpdateDTO, query);
        _context.Staff.Update(staff);

        //删除旧有角色
        var oldStaffRole = await _context.StaffRole
            .Where(a => a.StaffId == query.Id)
            .ToListAsync();
        _context.StaffRole.RemoveRange(oldStaffRole);

        //处理员工角色
        if (staffIUpdateDTO.RoleList != null)
            foreach (var item in staffIUpdateDTO.RoleList)
            {
                var newStaffRole = new StaffRoleModel
                {
                    Id = Guid.NewGuid(),
                    StaffId = query.Id,
                    RoleId = Guid.Parse(item)
                };
                _context.StaffRole.Add(newStaffRole);
            }

        //保存数据
        await _context.SaveChangesAsync();
        return RequestResponse.OK(staffIUpdateDTO.Id);
    }

    #endregion

    #region 删除员工

    public async Task<RequestResponseModel> DeleteStaff(SingleIdDTO deleteDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.Staff, deleteDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("员工Id无效");

        //删除操作
        _context.Staff.Remove(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion

    #region 批量删除员工

    public async Task<RequestResponseModel> DeleteArrayStaff(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.Staff
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("员工Id无效");
        ;

        //删除员工关联角色
        var staffRole = await _context.StaffRole
            .Where(a => idArrayDTO.Ids.Contains(a.StaffId.ToString()))
            .ToListAsync();

        //删除操作
        _context.StaffRole.RemoveRange(staffRole);
        _context.Staff.RemoveRange(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "删除成功");
    }

    #endregion

    #region 初始化

    //数据库
    private readonly DatabaseContext _context;

    //自动映射
    private readonly IMapper _mapper;

    //构造注入
    public StaffService(DatabaseContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    #endregion
}